<?php
/*
 * Aclass_cash
 * abans@qq.com
 */
class Com_cash{
	function  __construct($appid='') {
		$this->cname = 'Acan:cash:';
		$this->_SS = Afun_session();
		$this->cash = Afun_db()->model(Acan_table_danhao_cash);
		$this->info = Afun_db()->model(Acan_table_user_info);
	}
	//增加用户余额
	function cash_add($uid,$price,$cg='money',$type='0',$cash_id='',$rid='',$dnum=1,$dtype='m'){
		$info = Afun_obj_arr($this->info->ofind(array('uid'=>$uid)));
		if($cg=='free'){
			$info['free'] = $info['free']+$price;
			if($dnum>0){
				$info['free_date'] = Afun_time_date(Afun_time_ex(time(),$dnum,$dtype));
			}
		}elseif($cg=='cash'){
			$info['cash'] = $info['cash']+$price;
		}elseif($cg=='money'){
			$info['money'] = $info['money']+$price;
		}
		if($type>0){
			$cash = array('uid'=>$uid,'cash_id'=>$cash_id,'cash'=>$price,'buydate'=>Afun_get_time(),'update'=>Afun_get_time(),'type'=>$type);
			if(!empty($rid)) $cash['rid'] = $rid;
			$this->cash->save($cash);
		}
		$rs = $this->info->save($info);
		return $rs;
	}
	//扣除用户余额
	function cash_minus($uid,$price,$cg='money',$type='0',$cash_id='',$rid=''){
		$comp = false;
		$info = Afun_obj_arr($this->info->ofind(array('uid'=>$uid)));
		//赠送余额失效置为0
		if(strtotime($info['free_date'])<time()){$info['free']=0;}
		$total = $info['money']+$info['cash']+$info['free'];
		if($total<$price){
			return -1;//余额不足
		}
		if($cg=='free'){
			if($info['free']>0 && strtotime($info['free_date'])>time()){
				if($info['free']>=$price){
					$info['free'] = $info['free']-$price;
					$comp=true;
				}else{
					$price=$price-$info['free'];
					$info['free']=0;
				}
			}
			if(!$comp && $info['cash']>0){
				if($info['cash']>=$price){
					$info['cash'] = $info['cash']-$price;
					$comp=true;
				}else{
					$price=$price-$info['free'];
					$info['free']=0;
				}
			}
		}
		if(!$comp && $info['money']>0){
			$info['money'] = $info['money']-$price;
		}
		if($type>0){
			$cash = array('uid'=>$uid,'cash_id'=>$cash_id,'cash'=>'-'.$price,'buydate'=>Afun_get_time(),'update'=>Afun_get_time(),'type'=>$type,'rid'=>$rid);
			$this->cash->save($cash);
		}
		$rs = $this->info->save($info);
		return $rs;
	}
}
?>
